<template>
  <div class="survey-edit">
    <div class="survey-top-bar al-flex-between">
      <div></div>
      <div style="margin: 0 20px">
        <span style="font-size:14px;color: #2c3e50;">问卷时间：</span>
        <span style="margin-right: 10px;">
          <el-date-picker v-model="surveyTime"
                          type="daterange"
                          size="small"
                          range-separator="至"
                          start-placeholder="开始日期"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          end-placeholder="结束日期">
          </el-date-picker>
        </span>
        <el-button :loading="saveLoading" size="mini" type="primary"
                   :disabled="!canSave"
                   @click="saveServey">保存
        </el-button>
      </div>
    </div>

    <div class="survey-edit-wapper al-content">
      <div class="survey-e-left al-content">
        <div class="survey-question" v-for="(row,index) in questionTypes" :key="index">
          <h5>{{ row.title }}</h5>
          <div class="quest-type">
            <el-tag color="#fff" v-for="(child,index) in row.children"
                    :key="index" @click="addQuestion(child)">{{ child.label }}
            </el-tag>
          </div>
        </div>
      </div>

      <div class="survey-e-right">
        <div class="questions">

          <div class="questions-bar">
            <el-tabs v-model="currentTabs" type="border-card" @tab-click="handleTabs"
                     @tab-remove="tabRemove"
                     :before-leave="tabsBeforeLeave">
              <el-tab-pane :key="item.name" v-for="(item, index) in tableTabs" :label="item.title"
                           :closable="item.closed" :name="item.name"/>
              <el-tab-pane name="addBtn"><span slot="label">+</span></el-tab-pane>
            </el-tabs>
          </div>

          <div class="survey-main ">
            <div v-for="(q,index) in currentQuestions" :key="index"
                 :class="surveyClass(q)">
              <wx-survey style="flex: 0.99;" :question="q"/>
              <i class="el-icon-delete" style="color:#2c3e50;cursor:pointer;"
                 v-if="!['sTitle','sNotice','sEnd'].includes(q.type)"
                 @click="removeQuestion(index,q.index)"/>
              <span v-if="errMap ?errMap.id===q.index : false" class="err-msg">{{ errMap ? errMap.err : '' }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="mobile-preview">
        <!--        <div style="font-size:10px;">预览非最终效果</div>-->
        <wx-survey-preview :survey="survey" :currentIndex="currentTabs"/>
      </div>
    </div>
  </div>
</template>

<script>
import {INIT_SERVEY, surveyTypes} from "@/utils/qywx/const";
import WxSurvey from "@/components/wxqy/wxservey/wxSurvey";
import WxSurveyPreview from "@/components/wxqy/wxservey/wxSurveyPreview";
import {surveyDetail, surveyEdit} from "@/api/wxqy/ActivityApis";
import {surveyValidate} from "@/utils/validate";

export default {
  name: "edit",
  components: {WxSurveyPreview, WxSurvey},
  data() {
    return {
      id: 0,
      questionTypes: surveyTypes(),
      currentTabs: '0',
      tableTabs: [
        {title: '第1页', name: '0', closed: false},
        {title: '结束页', name: '-1', closed: false},
      ],
      errMap: {},
      surveyTime: [],
      survey: [],
      currentQuestions: [],
      saveLoading: false,
      canSave: true
    }
  },
  methods: {
    handleTabs() {
      this.currentPage()
    },
    tabsBeforeLeave(activeName) {
      if (activeName === 'addBtn') {
        let index = this.tableTabs.length
        let q = {title: '第' + index + '页', name: (index - 1) + '', closed: true}
        this.tableTabs.splice(index - 1, 0, q)
        this.currentTabs = (index - 1) + ''
        this.currentQuestions = []
        return false
      }
      return true
    },
    tabRemove(index) {
      this.tableTabs.splice(index, 1)
      for (let i = 1; i < this.tableTabs.length - 1; i++) {
        this.tableTabs[i].title = '第' + (i + 1) + '页'
        this.tableTabs[i].name = i + ''
      }
      this.currentTabs = (index + '' === this.currentTabs) ? '0' : parseInt(this.currentTabs) - 1 + ''
      this.currentPage()
    },
    currentPage() {
      this.currentQuestions = this.survey.filter(s => s.page === parseInt(this.currentTabs))
    },
    addQuestion(child) {
      let page = parseInt(this.currentTabs), index = this.survey.length
      if (page < 0) return
      let question = Object.assign({page: page, index: index, topic: {title: child.label}}, child)
      if (child.name === 'input') {
        question.topic = {
          title: question.placeholder, required: true
        }
      }
      this.survey.push(question)
      this.currentQuestions.push(question)
    },
    removeQuestion(index, surverIndex) {
      this.currentQuestions.splice(index, 1)
      this.survey = this.survey.filter(s => s.index !== surverIndex)
    },
    surveyClass(q) {
      return {
        'survey-item': q.page > -1,
        'survey-end': q.page === -1,
        'survey-err': this.errMap ? this.errMap.id === q.index : false
      }
    },
    saveServey() {
      if (!this.surveyTime.length) {
        this.$message.error('请设置问卷时间')
        return
      }
      this.errMap = {}
      this.errMap = surveyValidate(this.survey);
      if (!this.errMap) {
        let params = {
          id: this.id, survey: this.survey,
          startTime: this.surveyTime[0], endTime: this.surveyTime[1]
        }
        this.saveLoading = true
        surveyEdit(params).then(e => {
          let msg = (this.id ? '编辑' : '新增') + '问卷成功'
          this.$message.success(msg);
          this.$router.push({path: 'list'})
        }).finally(() => this.saveLoading = false)
      } else {
        this.$message.error(`请检查第${this.errMap.page + 1}页表单内容`)
      }
    },
  },
  created() {
    this.id = this.$route.query.id || 0
    if (this.id) {
      surveyDetail({id: this.id}).then(e => {
        let {questions, beginTime, endTime} = e.data
        this.survey = JSON.parse(questions)
        this.surveyTime = [beginTime, endTime]
        this.currentPage()
        this.canSave = new Date().getTime() < new Date(endTime).getTime()
      })
    } else {
      this.survey = INIT_SERVEY()
      this.currentPage()
    }
  }
}
</script>

<style scoped lang="scss">
.survey-edit-wapper, .survey-e-right {
  display: flex;
  justify-content: space-around;
  align-items: flex-start;
}

.survey-top-bar {
  position: sticky;
  top: 0;
  height: 50px;
  background-color: #fff;
  z-index: 999;
}

.survey-e-left {
  position: sticky;
  top: 60px;
  flex: 0 0 17%;
  background-color: #fff;

  margin-right: 10px;
  height: 600px;

  .survey-question {
    text-align: center;

    .quest-type {
      display: flex;
      flex-wrap: wrap;

      span {
        margin: 0 10px 10px 10px;
        width: 5.6em;
        cursor: pointer;
        border-color: #ccc;
        color: #2c3e50;
      }
    }
  }
}

.survey-e-right {
  flex: 1;

  .questions {
    width: 100%;
    min-height: calc(100vh - 120px);
    background-color: #fff;

    ::v-deep.el-tabs__content {
      display: none;
    }

    .questions-bar {
      position: sticky;
      top: 50px;
      z-index: 999;

      ::v-deep.el-tabs__item:not(.is-disabled) {
        .el-icon-close {
          display: none;
        }
      }

      ::v-deep.el-tabs__item:not(.is-disabled):hover {
        .el-icon-close {
          display: inherit;
        }
      }

      ::v-deep.el-tabs__item.is-active {
        .el-icon-close {
          display: inherit !important;
        }
      }
    }

    .survey-end {
      padding: 20px 0;
    }

    .survey-item {
      background-color: aliceblue;
      border-radius: 10px;
      padding: 20px 0;
      margin: 14px;
      position: relative;

      .el-icon-delete {
        display: none;
        position: absolute;
        right: 10px;
        top: 30px;
        color: #f55555 !important;
      }
    }

    .survey-item:hover {
      .el-icon-delete {
        display: block;
      }
    }
  }
}

.mobile-preview {
  position: sticky;
  top: 60px;
  width: 300px;
  height: 500px;
  margin-left: 10px;
  background-color: #fff;
}

.survey-err {
  border: 1px solid #f56969;

  .err-msg {
    display: block;
    margin-left: 20px;
    margin-top: 10px;
    font-size: 12px;
    color: #f55959;
  }
}
</style>
